package com.boco.common.util;

import org.springframework.data.domain.Page;
import org.springframework.hateoas.PagedResources;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @author pandengke/pdkkpdk@163.com
 * @date 2018/11/15
 */
public class ResponseUtils {

    public static Object emptyResources(PagedResources.PageMetadata page, String resources) {
        Map<String, Object> result = new HashMap<>();
        HashMap<String, Object> map = new HashMap<>();
        map.put(resources, new ArrayList<>());
        result.put("_embedded", map);
        result.put("page", page);
        return result;
    }


    public static Object pageable(Page<Object> page, String resources) {
        PagedResources.PageMetadata pm = new PagedResources.PageMetadata(page.getSize(), page.getNumber(), page.getTotalElements());
        /*空列表也需要展示字段，以便前端统一解析*/
        if (page.getContent().isEmpty()) {
            return ResponseUtils.emptyResources(pm, resources);
        }
        return new PagedResources<>(page.getContent(), pm, new ArrayList<>());
    }
}
